package cn.lijian.goods.admin.book.web.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.management.RuntimeErrorException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import cn.itcast.commons.CommonUtils;
import cn.lijian.goods.book.domain.Book;
import cn.lijian.goods.book.service.BookService;
import cn.lijian.goods.category.domain.Category;
import cn.lijian.goods.category.service.CategoryService;

public class AdminAddBookServlet extends HttpServlet {
	

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//创建工厂
		FileItemFactory factory=new DiskFileItemFactory();
		//创建解析器
		ServletFileUpload sfu=new ServletFileUpload(factory);
		sfu.setFileSizeMax(80*1024);//设置单个文件上传最大 大小 为 80 k
		//解析 request ，得到 list<FileItem>
		List<FileItem>fileItemList=null;
		try {
			fileItemList=sfu.parseRequest(request);
		} catch (FileUploadException e) {
			//如果出现异常，说明单个文件超出 80 k
			error("上传的文件超出了 80 k ",request,response);
			return ;
		}
		//把 list<FileItem> 封装到 Book 对象中
		Map<String,Object>map=new HashMap<String,Object>();
		for(FileItem fileItem:fileItemList){
			if(fileItem.isFormField()){//如果是普通表单字段也就是没有 <file> 中的，其余的都有
				map.put(fileItem.getFieldName(), fileItem.getString("utf-8"));
			}
		}
		Book book=CommonUtils.toBean(map, Book.class);
		Category category=CommonUtils.toBean(map, Category.class);
		book.setCategory(category);
		
		FileItem fileItem=fileItemList.get(1);//获取大图，这个 1 是因为 在页面中 file 是第二个 参数
		String fileName=fileItem.getName();//截取文件名，因为部分浏览器上传到的是绝对路径
		int index=fileName.lastIndexOf("\\");
		if(index!=-1){
			fileName=fileName.substring(index+1);
		}
		fileName=CommonUtils.uuid()+"_"+fileName;//给文件名加 uuid ，避免重名
		//检验文件的拓展名
		if(!fileName.toLowerCase().endsWith(".jpg")){
			error("上传的文件必须是 jpg ",request,response);
			return ;
		}
		
		//校验图片尺寸
		String savePath=this.getServletContext().getRealPath("/book_img");
		File destFile=new File(savePath,fileName);
		try {
			fileItem.write(destFile);//把临时文件保存到指定路径，再删除临时文件
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		
		ImageIcon icon=new ImageIcon(destFile.getAbsolutePath());
		java.awt.Image image=icon.getImage();
		if(image.getWidth(null)>350||image.getHeight(null)>350){
			error("您上传的文件图片尺寸超出了 350 * 350",request,response);
			destFile.delete();
			return ;
		}
		
		//把图片的路径保存给 book 对象
		book.setImage_w("book_img/"+fileName);
		
		
		fileItem=fileItemList.get(2);//获取小图
		fileName=fileItem.getName();//截取文件名，因为部分浏览器上传到的是绝对路径
		index=fileName.lastIndexOf("\\");
		if(index!=-1){
			fileName=fileName.substring(index+1);
		}
		fileName=CommonUtils.uuid()+"_"+fileName;//给文件名加 uuid ，避免重名
		//检验文件的拓展名
		if(!fileName.toLowerCase().endsWith(".jpg")){
			error("上传的文件必须是 jpg ",request,response);
			return ;
		}
		
		//校验图片尺寸
		savePath=this.getServletContext().getRealPath("/book_img");
		destFile=new File(savePath,fileName);
		try {
			fileItem.write(destFile);//把临时文件保存到指定路径，再删除临时文件
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		
		icon=new ImageIcon(destFile.getAbsolutePath());
		image=icon.getImage();
		if(image.getWidth(null)>350||image.getHeight(null)>350){
			error("您上传的文件图片尺寸超出了 350 * 350",request,response);
			destFile.delete();
			return ;
		}
		
		//把图片的路径保存给 book 对象
		book.setImage_b("book_img/"+fileName);
		book.setBid(CommonUtils.uuid());
		
		BookService bookService=new BookService();
		bookService.add(book);
		
		request.setAttribute("msg", "添加图书成功");
		request.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(request, response);
		
		
	}
	/**
	 * 保存错误信息，转发到 add.jsp 
	 * @param msg
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @author lijian
	 */
	private void error(String msg,HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setAttribute("msg", msg);
		request.setAttribute("parents", new CategoryService().findParents());
		request.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(request, response);
	}

}
